﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Janus.Windows.EditControls;
using Janus.Windows.GridEX;
using Janus.Windows.Schedule;
using Janus.Windows.UI.Dock;
using YiLe.DataForms;
using YiLe.View.Login;
using YiLe.View.Users;
using BorderStyle = Janus.Windows.GridEX.BorderStyle;
using HideSelection = Janus.Windows.GridEX.HideSelection;

namespace YiLe.UI
{
    public partial class LaterMainForm : Form
    {
        public LaterMainForm()
        {
            InitializeComponent();
        }

        private bool selectFolder;
        private bool initialized;
        public void InitializeMainForm()
        {
            YiLeSystemApp.RootFolder.ContactsFolder.NavigatorPanel = this.uipContacts;

            //fill treeviews:
            this.SetGridEXTreeProperties(this.treeContacts);

            CreateTreeNode(this.treeContacts, YiLeSystemApp.RootFolder.ContactsFolder);

            //this.treeContacts.Row = 1;//TODO:ROW ONLY ONE

            selectFolder = true;

            initialized = true;
        }

        private void CreateTreeNode(GridEX grid, ApplicationFolder folder)
        {
            grid.DataSource = new ApplicationFolder[]{folder};
            grid.ExpandRecords();
        }

        private void SetGridEXTreeProperties(GridEX grid)
        {
            grid.BorderStyle = BorderStyle.None;
            grid.AllowEdit = InheritableBoolean.False;
            grid.HideSelection = HideSelection.HighlightInactive;
            grid.KeepRowSettings = true;
            grid.RootTable = new GridEXTable();
            grid.SelectOnExpand = true;
            grid.ColumnAutoResize = true;
            grid.GridLines = GridLines.None;
            grid.GroupByBoxVisible = false;
            grid.ColumnHeaders = InheritableBoolean.False;
            grid.FocusStyle = FocusStyle.None;
            grid.RootTable.HierarchicalMode = HierarchicalMode.SelfReferencingChildList;
            GridEXColumn col = null;
            col = grid.RootTable.Columns.Add("FolderName", ColumnType.ImageAndText);
            col.Selectable = false;
            grid.RootTable.SelfReferencingSettings.ExpandColumn = col;
            grid.RootTable.SelfReferencingSettings.AutoSizeColumnOnExpand = true;
            grid.RootTable.SelfReferencingSettings.ChildListMember = "Folders";
        }

        /// <summary>
        ///视图属性 
        /// </summary>
        private ApplicationFolder mCurrentFolder;
        public ApplicationFolder CurrentFolder
        {
            get
            {
                return mCurrentFolder;
            }
            set
            {
                if (mCurrentFolder != value)
                {
                    if (!this.UpdateCurrentFolder())
                    {
                        return;
                    }
                    System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
                    if (value != null)
                    {
                        //force the folder to load its data and its content view control
                        value.Load();
                    }

                    if (mCurrentFolder != null)
                    {
                        //remove preview control if it exists
                        this.previewPager.ChildControl = null;
                        //unload current folder
                        mCurrentFolder.Unload();
                    }
                    mCurrentFolder = value;

                    this.OnCurrentFolderChanged();
                    this.ResetStatusBarInfo();//status的重置
                    System.Windows.Forms.Cursor.Current = Cursors.Default;
                }
            }
        }
        /// <summary>
        /// 更新folder内容
        /// </summary>
        private void OnCurrentFolderChanged()
        {
           if (mCurrentFolder != null)
            {
                //select navigator panel in case that CurrentFolder is set in code
                if (mCurrentFolder.NavigatorPanel != null)
                {
                    Janus.Windows.GridEX.GridEX treeControl = this.PanelTree(mCurrentFolder.NavigatorPanel);
                    if (treeControl != null)
                    {
                        this.SelectFolderInTree(treeControl, mCurrentFolder);
                    }
                    this.uipNavigator.SelectedPanel = mCurrentFolder.NavigatorPanel;

                }
                this.uipContentGroup.Text = mCurrentFolder.FolderName;
                this.uipContentGroup.ImageKey = mCurrentFolder.ImageKey;
                this.SetViews();
                //设置展示详细preview信息,但是无法展示到PreviewPage之中
                if (mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.ReadingPane))
                {
                    this.previewPager.MinSize = mCurrentFolder.PreviewControl.FullSize;
                    this.visualStyleManager1.AddControl(mCurrentFolder.PreviewControl, true);
                    this.previewPager.ChildControl = mCurrentFolder.PreviewControl;
                    mCurrentFolder.PreviewControl.Visible = true;
                }
                this.cmdRecordsEdit.ImageKey = mCurrentFolder.EditImageKey;
                this.cmdRecordsEdit.LargeImageKey = mCurrentFolder.EditImageKey;
                this.cmdRecordsNew.ImageKey = mCurrentFolder.NewImageKey;
            }
            EnableCommands();
        }
        /// <summary>
        /// 设置Views
        /// </summary>
        private void SetViews()
        {
            UIPanel viewsPanel = null;
            if (this.uipNavigator.SelectedPanel == this.uipContacts)
            {
                viewsPanel = this.uipContactFolderView;
            }
            else if (this.uipNavigator.SelectedPanel == this.uipProductsAndOrders)
            {
                viewsPanel = this.uipProdAndOrdersViews;
            }
            if (viewsPanel != null)
            {
                if (mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.MultipleViews))
                {
                    /*Janus.Windows.EditControls.UIRadioButton optionButton = null;
                    int buttonTop = 4;
                    viewsPanel.InnerContainer.Controls.Clear();
                    UIPager optionsPager = new UIPager();
                    optionsPager.Dock = DockStyle.Fill;
                    //optionsPager.VisualStyleManager = this.VisualStyleManager1;
                    Janus.Windows.EditControls.UIGroupBox gBox = new Janus.Windows.EditControls.UIGroupBox();
                    gBox.BackgroundStyle = Janus.Windows.EditControls.BackgroundStyle.Default;
                    gBox.BackColor = SystemColors.Window;
                    gBox.BorderColor = Color.Transparent;
                    gBox.Height = 0;
                    //viewsPanel.InnerContainer.AutoScroll = true;
                    foreach (FolderView folderView in mCurrentFolder.Views)
                    {

                        optionButton = this.CreateOptionForView(folderView, viewsPanel.InnerContainer.Width);
                        //Select default view
                        if (folderView == mCurrentFolder.CurrentView)
                        {
                            optionButton.Checked = true;
                        }
                        optionButton.Location = new Point(8, buttonTop);
                        buttonTop = buttonTop + optionButton.Height;
                        optionButton.CheckedChanged += new EventHandler(this.ViewOption_CheckedChanged);
                        gBox.Controls.Add(optionButton);
                    }
                    gBox.Height = optionButton.Bounds.Bottom;
                    gBox.Width = viewsPanel.InnerContainer.Width;
                    optionsPager.MinSize = new Size(0, gBox.Height);
                    optionsPager.ScrollMode = ScrollMode.Vertical;
                    optionsPager.ChildControl = gBox;
                    viewsPanel.InnerContainer.Controls.Add(optionsPager);
                    viewsPanel.Closed = false;*/

                }
                else
                {
                    viewsPanel.Closed = true;
                }
                //this.VisualStyleManager1.AddControl(viewsPanel, true);

            }

            ShowCurrentFolderView();
        }
        /// <summary>
        /// SetView 展示View
        /// </summary>
        private void ShowCurrentFolderView()
        {
            if (mCurrentFolder != null)
            {
                ContentViewControl ctl = mCurrentFolder.CurrentContentView;
                if (ctl != null)
                {
                    ctl.FolderView = mCurrentFolder.CurrentView;
                    /*if (ctl is ScheduleView)
                    {
                        //bind the date selector to the schedule in the view
                        this.dateSelector.Schedule = ((ScheduleView)ctl).Schedule;
                        this.ScheduleOwnersList.DataSource = ((ScheduleView)ctl).Schedule.Owners;

                    }*/
                    CurrentContentView = ctl;

                    mCurrentContentView.Focus();
                    switch (mCurrentFolder.CurrentView.ReadingPaneLocation)
                    {
                        case ReadingPaneLocation.Off:
                            this.uipContentPreview.Closed = true;
                            break;
                        case ReadingPaneLocation.Right:
                            this.uipContentGroup.GroupStyle = PanelGroupStyle.VerticalTiles;
                            this.uipContentPreview.Closed = false;
                            break;
                        case ReadingPaneLocation.Bottom:
                            this.uipContentGroup.GroupStyle = PanelGroupStyle.HorizontalTiles;
                            this.uipContentPreview.Closed = false;
                            break;
                    }
                    //貌似设置preview的展示样式
                    if (mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.ReadingPane))
                    {
                        //TODO:展示preview 的datasource
                        //mCurrentFolder.PreviewControl.BindingContext = mCurrentContentView.BindingContext;
                        //mCurrentFolder.PreviewControl.DataSource = mCurrentContentView.DataSource;
                        //mCurrentFolder.PreviewControl.AllowEdit = false;
                        //this.previewPager.ChildControl = mCurrentFolder.PreviewControl;
                    }
                }
                else
                {
                    CurrentContentView = null;
                }
            }
            ResetStatusBarInfo();
            EnableCommands();
        }
        public void ResetStatusBarInfo()
		{
            if ((mCurrentContentView == null))
            {
                this.sbInfoText.Text = "";
            }
            else
            {

                this.sbInfoText.Text = mCurrentContentView.StatusBarInfo;
            }
            this.sbDate.Text = System.DateTime.Today.ToString("d");
		}
        /// <summary>
        /// SetView CurrentContentView
        /// </summary>
        public ContentViewControl CurrentContentView
        {
            get
            {
                return mCurrentContentView;
            }
            set
            {
                if (mCurrentContentView != value)
                {
                    if (mCurrentContentView != null)
                    {
                        //force CurrentContentView to save its settings
                        mCurrentContentView.SaveSettings();
                        this.ribbon1.UnmergeRibbon();
                        this.uipContentContainer.Controls.Remove(mCurrentContentView);
                        mCurrentContentView.CurrentItemChanged -= new EventHandler(this.CurrentItemChanged);
                    }
                    mCurrentContentView = value;
                    if (mCurrentContentView != null)
                    {
                        mCurrentContentView.Dock = DockStyle.Fill;
                        mCurrentContentView.Bounds = this.uipContentContainer.ClientRectangle;
                        mCurrentContentView.Visible = false;
                        this.uipContentContainer.Controls.Add(mCurrentContentView);
                        //this.VisualStyleManager1.AddControl(mCurrentContentView, true);
                        if (mCurrentContentView.RibbonControl != null)
                        {
                            this.ribbon1.MergeRibbon(this.mCurrentContentView.RibbonControl);
                        }
                        mCurrentContentView.Visible = true;
                        this.OnCurrentItemChanged();
                        mCurrentContentView.CurrentItemChanged += new EventHandler(this.CurrentItemChanged);

                    }
                    this.EnableCommands();

                }
            }
        }
        private void CurrentItemChanged(object sender, EventArgs e)
        {
            OnCurrentItemChanged();
        }
        private void OnCurrentItemChanged()
        {

            if (this.CurrentContentView != null & this.CurrentContentView.CurrentItem != null)
            {
                this.previewPager.Visible = true;
            }
            else
            {
                this.previewPager.Visible = false;
            }
            if (CurrentContentView != null)
            {
                this.cmdRecordsDelete.Enabled = CurrentContentView.CanDelete;
                this.cmdRecordsEdit.Enabled = CurrentContentView.CanEdit;
            }
        }
        /// <summary>
        /// setViews 创建Option?
        /// </summary>
        /// <param name="view"></param>
        /// <param name="width"></param>
        /// <returns></returns>
        private UIRadioButton CreateOptionForView(FolderView view, int width)
        {
            Janus.Windows.EditControls.UIRadioButton viewControl = new Janus.Windows.EditControls.UIRadioButton();

            viewControl.Text = view.ViewName;
            viewControl.Tag = view;
            viewControl.BackColor = Color.Transparent;
            //viewControl.VisualStyleManager = this.VisualStyleManager1;

            viewControl.WordWrap = false;
            viewControl.Size = new Size(width - 15, this.Font.Height + 4);
            viewControl.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            return viewControl;
        }
        /// <summary>
        /// SetView创建ViewOption
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ViewOption_CheckedChanged(object sender, EventArgs e)
        {
            Janus.Windows.EditControls.UIRadioButton optChanged = null;
            optChanged = (Janus.Windows.EditControls.UIRadioButton)sender;
            if (optChanged.Checked)
            {
                mCurrentFolder.CurrentView = (FolderView)optChanged.Tag;
                ShowCurrentFolderView();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tree"></param>
        /// <param name="folder"></param>
        private void SelectFolderInTree(GridEX tree, ApplicationFolder folder)
        {
            Janus.Windows.GridEX.GridEXRow row = null;
            row = tree.GetRow(folder);
            if (row != null)
            {
                tree.MoveTo(row);
            }
        }
        /// <summary>
        /// 设置按钮的状态，4处调用
        /// </summary>
        private void EnableCommands()
        {
            if ((mCurrentContentView == null) || !mCurrentContentView.Printable)
            {
                this.rcmdPrint.Enabled = false;
                this.rcmdPrintPreview.Enabled = false;
            }
            else
            {
                this.rcmdPrint.Enabled = true;
                this.rcmdPrintPreview.Enabled = true;
            }
            if (this.CurrentFolder != null && this.mCurrentFolder.Supports(ApplicationFolder.FolderFeatures.ReadingPane))
            {
                this.rbngReadingPane.Visible = true;
                this.rcmdReadingPaneRight.Enabled = true;
                this.rcmdReadingPaneOff.Enabled = true;
                this.rcmdReadingPaneBottom.Enabled = true;
                switch (this.CurrentFolder.CurrentView.ReadingPaneLocation)
                {
                    case ReadingPaneLocation.Off:
                        this.rcmdReadingPaneOff.Checked = true;
                        break;
                    case ReadingPaneLocation.Bottom:
                        this.rcmdReadingPaneBottom.Checked = true;
                        break;
                    case ReadingPaneLocation.Right:
                        this.rcmdReadingPaneRight.Checked = true;
                        break;
                }
            }
            else
            {
                this.rbngReadingPane.Visible = false;
                this.rcmdReadingPaneRight.Enabled = false;
                this.rcmdReadingPaneOff.Enabled = false;
                this.rcmdReadingPaneBottom.Enabled = false;
            }
            if (mCurrentContentView != null)
            {
                this.cmdRecordsDelete.Enabled = (this.mCurrentContentView.CanDelete);
                this.cmdRecordsEdit.Enabled = (this.mCurrentContentView.CanEdit);

            }
            else
            {
                this.cmdRecordsEdit.Enabled = false;
                this.cmdRecordsDelete.Enabled = false;
            }
            if (mCurrentFolder != null)
            {
                this.cmdRecordsNew.Enabled = mCurrentFolder.CanAdd;
            }
            else
            {
                this.cmdRecordsNew.Enabled = false;
            }
        }
        private ContentViewControl mCurrentContentView;



        private Janus.Windows.GridEX.GridEX PanelTree(UIPanelBase panel)
        {
            if (panel.Name == this.uipContacts.Name)
            {
                return this.treeContacts;
            }
            else
            {
                return null;
            }
        }

        private void OnContactsPanelSelected()
        {
            if (this.treeContacts.Row < 0)
            {
                if (this.treeContacts.RowCount >= 1)
                {
                    this.treeContacts.Row = 1;
                }
            }
            else
            {
                this.CurrentFolder = (ApplicationFolder)(this.treeContacts.GetRow().DataRow);
            }
        }


        private void treeContacts_CurrentCellChanged(object sender, EventArgs e)
        {
            GridEX tree = null;
            tree = (GridEX) sender;
            if (! this.uipNavigator.SelectedPanel.Contains(tree))
            {
                return;
            }
            GridEXRow currentRow = null;
            currentRow = tree.GetRow();
            if (currentRow != null)
            {
                CurrentFolder = (ApplicationFolder) currentRow.DataRow;
            }
        }

        private void treeContacts_CurrentCellChanging(object sender, Janus.Windows.GridEX.CurrentCellChangingEventArgs e)
        {
            if (!this.UpdateCurrentFolder())
            {
                e.Cancel = true;
            }
        }

        private bool UpdateCurrentFolder()
        {
            if (this.CurrentFolder != null)
            {
                return this.CurrentFolder.UpdateData();
            }
            else
            {
                return true;
            }
        }

        private void treeContacts_FormattingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)
        {
            if (e.Row.RowType == Janus.Windows.GridEX.RowType.Record)
            {
                //todo:picture is not added
                ApplicationFolder folder = (ApplicationFolder) e.Row.DataRow;
                e.Row.Cells["FolderName"].ImageKey = folder.ImageKey;
            }

        }
    }
}
